package com.xiong.serializeutils;

import java.io.*;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/8/4 13:56
 * @since JDK 1.8
 */
public class SerializeUtils {

    public static <T> byte[] serizlize(T t) throws Exception{
        if(!(t instanceof Serializable)){
            throw new Exception("未实现 Serializable ");
        }
        return serizlizeByObject(t);
    }

    public static <T> T deserialize(byte[] bytes,Class<T> cls) throws Exception{
        if(!(cls instanceof Serializable)){
            throw new Exception("未实现 Serializable ");
        }
        return (T) deserializeByObject(bytes);
    }

    /*
     * 序列化
     * */
    public static byte[] serizlizeByObject(Object object){
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(baos != null){
                    baos.close();
                }
                if (oos != null) {
                    oos.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }

    /*
     * 反序列化
     * */
    public static Object deserializeByObject(byte[] bytes){
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;
        try{
            bais = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bais);
            return ois.readObject();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try {

            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }


}
